<?php

declare(strict_types=1);

namespace App\CustHub\Model;

use App\Common\Constants\ErrorCode;
use App\CustHub\Service\CommonService;
use App\Exception\BusinessException;
use Mine\MineModel;
use function Yansongda\Supports\data_get;

/**
 * @property int $id 主键
 * @property int $corp_id 
 * @property int $main_uid 主账号id
 * @property int $uid 私域用户ID
 * @property int $group_id 分组id
 * @property string $title 标题
 * @property array $robot_ids 机器人
 * @property int $answer_times_type 1全部时间  2自定义时间
 * @property int $status 1开启 0关闭
 * @property string $answer_start 应答开始时间
 * @property string $answer_end 应答结束时间
 * @property int $answer_limit_max 应答间隔最大值
 * @property int $answer_limit_min 应答间隔最小值
 * @property int $answer_type 1按客户  2按条件 
 * @property int $open_custom 
 * @property int $open_crowd 
 * @property int $is_answer_white 是否应答白名单用户
 * @property int $is_answer_other_online 是否应答系统中别的企业微信号
 * @property int $open_keyword 是否开启关键词应答
 * @property int $open_image 是否开启文应答
 * @property int $open_default 是否开启默认应答
 * @property \Carbon\Carbon $created_at 
 * @property \Carbon\Carbon $updated_at 
 * @property string $answer_date_start 按日期开始时间
 * @property string $answer_date_end 按日期结束时间
 * @property array $answer_time_config 应答配置
 * @property-read mixed $crowd_ids 
 * @property-read mixed $custom_ids 
 * @property-read mixed $condition_conf 条件配置
 * @property-read mixed $auto_smart_tag 自动智能标签
 * @property-read mixed $auto_enterprise_tag 自动企微标签
 * @property-read mixed $keyword_conf 
 * @property-read mixed $image_conf 图片应答配置
 * @property-read mixed $default_conf 默认应答配置
 */
class ChSmartAnswer extends MineModel
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'ch_smart_answer';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'corp_id', 'main_uid', 'uid', 'group_id', 'title', 'robot_ids', 'answer_times_type', 'status', 'answer_start', 'answer_end', 'answer_limit_max', 'answer_limit_min', 'answer_type', 'crowd_ids', 'custom_ids', 'open_custom', 'open_crowd', 'condition_conf', 'is_answer_white', 'is_answer_other_online', 'auto_smart_tag', 'auto_enterprise_tag', 'open_keyword', 'keyword_conf', 'open_image', 'image_conf', 'open_default', 'default_conf', 'created_at', 'updated_at', 'answer_date_start', 'answer_date_end', 'answer_time_config'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'corp_id' => 'integer', 'main_uid' => 'integer', 'uid' => 'integer', 'group_id' => 'integer', 'robot_ids' => 'array', 'answer_times_type' => 'integer', 'status' => 'integer', 'answer_limit_max' => 'integer', 'answer_limit_min' => 'integer', 'answer_type' => 'integer', 'crowd_ids' => 'array', 'custom_ids' => 'array', 'open_custom' => 'integer', 'open_crowd' => 'integer', 'condition_conf' => 'array', 'is_answer_white' => 'integer', 'is_answer_other_online' => 'integer', 'auto_smart_tag' => 'array', 'auto_enterprise_tag' => 'array', 'open_keyword' => 'integer', 'keyword_conf' => 'array', 'open_image' => 'integer', 'image_conf' => 'array', 'open_default' => 'integer', 'default_conf' => 'array', 'created_at' => 'datetime', 'updated_at' => 'datetime', 'answer_time_config' => 'array'];

    public static $keywordStatic = [
        "guzze" => [
            [
                "key" => 1,
                "text" => "群消息@自己才回复",
                "checked" => false,
                "value" => "",
                "help" => "",
            ],
            [
                "key" => 2,
                "text" => "回复内容带上问题",
                "checked" => false,
                "value" => "",
                "help" => "",
            ],
            [
                "key" => 3,
                "text" => "回复群消息时@对方",
                "checked" => false,
                "value" => "",
                "help" => "",
            ],
            [
                "key" => 4,
                "text" => "自己可触发关键词",
                "checked" => false,
                "value" => "",
                "help" => "1、自己只能触发精准关键词；
2、注意回复问题中不要设置相关关键词，避免循环触发；",
            ],
            [
                "key" => 5,
                "text" => "同一对象同一问题{value}分钟内不重复回复",
                "checked" => false,
                "value" => 60,
                "help" => "",
            ]
        ],
        "guide" => "回复序号查看以下问题",
    ];

    public static $imageStatic = [
        "guzze" => [
            [
                "key" => 1,
                "text" => "收到{value}张图片后合并回复",
                "checked" => false,
                "value" => "",
                "help" => "",
            ],
            [
                "key" => 2,
                "text" => "汇总{value}秒内的图片消息合并回复",
                "checked" => false,
                "value" => "",
                "help" => "",
            ],
            [
                "key" => 3,
                "text" => "同一对象回复后{value}分钟内忽略其发来的图片@对方",
                "checked" => false,
                "value" => "",
                "help" => "",
            ],
        ],
        "content" => [],
    ];


    public static $defaultStatic = [
        "guzze" => [
            [
                "key" => 1,
                "text" => "群消息@自己才回复",
                "checked" => false,
                "value" => "",
                "help" => "",
            ],
            [
                "key" => 2,
                "text" => "回复群消息时@对方",
                "checked" => false,
                "value" => "",
                "help" => "",
            ],
            [
                "key" => 3,
                "text" => "同一对象同一问题{value}分钟内不重复回复",
                "checked" => false,
                "value" => "",
                "help" => "",
            ]
//            [
//                "key" => 4,
//                "text" => "触发默认应答{value}后延迟秒发送回复内容",
//                "checked" => false,
//                "value" => "",
//                "help" => "",
//            ]
        ],
        "content" => [],
        "delay"=> 60,
    ];

    public function getCrowdIdsAttribute()
    {
        return !empty($this->attributes['crowd_ids'])?json_decode($this->attributes['crowd_ids'],true):[];
    }

    public function getCustomIdsAttribute()
    {
        return !empty($this->attributes['custom_ids'])?json_decode($this->attributes['custom_ids'],true):[];
    }

    public function getConditionConfAttribute()
    {
        return !empty($this->attributes['condition_conf'])?json_decode($this->attributes['condition_conf'],true):[];
    }

    public function getAutoSmartTagAttribute()
    {
        return !empty($this->attributes['auto_smart_tag'])?json_decode($this->attributes['auto_smart_tag'],true):[];
    }

    public function getAutoEnterpriseTagAttribute()
    {
        return !empty($this->attributes['auto_enterprise_tag'])?json_decode($this->attributes['auto_enterprise_tag'],true):[];
    }

    public function getKeywordConfAttribute()
    {
        return !empty($this->attributes['keyword_conf'])?json_decode($this->attributes['keyword_conf'],true):[];
    }

    public function getImageConfAttribute()
    {
        return !empty($this->attributes['image_conf'])?json_decode($this->attributes['image_conf'],true):[];
    }

    public function getDefaultConfAttribute()
    {
        return !empty($this->attributes['default_conf'])?json_decode($this->attributes['default_conf'],true):[];
    }




    public static function saveAnswer($uid,$data,$id = 0)
    {
        $model = new self();
        if($id){
            $model = self::where('id',$id) -> first();
            if(empty($model)) throw new BusinessException(ErrorCode::NOT_ISSET,'数据不存在');
        }
        $model -> uid = $uid;
        if(!empty($data['title'])) $model -> title = $data['title'];
        $model -> group_id = data_get($data,'group_id',0);
        $model -> answer_times_type = $data['answer_times_type'];
        $model -> corp_id = $data['corp_id'];
        if($data['answer_times_type']==1){
            //$model -> answer_start = $data['answer_start'];
            //$model -> answer_end = $data['answer_end'];
        }else{
            //$model -> answer_date_start = $data['answer_date_start'];
            //$model -> answer_date_end = $data['answer_date_end'];
            !empty($data['answer_time_config']) && $model -> answer_time_config =  !is_array($data['answer_time_config']) ? json_decode($data['answer_time_config'],true):$data['answer_time_config'];

        }
        $model -> answer_limit_min = $data['answer_limit_min'];
        $model -> answer_limit_max = $data['answer_limit_max'];
        $model -> answer_type = $data['answer_type'];
        $model -> condition_conf = null;
        $model -> auto_smart_tag = null;
        $model -> auto_enterprise_tag = null;
        if($data['answer_type'] == 1){
           !empty($data['crowd_ids']) && $model -> crowd_ids =  !is_array($data['crowd_ids']) ? json_decode($data['crowd_ids'],true):$data['crowd_ids'];
           !empty($data['custom_ids']) && $model -> custom_ids = !is_array($data['custom_ids']) ? json_decode($data['custom_ids'],true):$data['custom_ids'];
        }else if($data['answer_type'] == 2){
            !empty($data['condition_conf']) &&
            $model -> condition_conf =  !is_array($data['condition_conf']) ? json_decode($data['condition_conf'],true):$data['condition_conf'];
        }
        $model -> is_answer_white = data_get($data,'is_answer_white',0);
        $model -> is_answer_other_online = data_get($data,'is_answer_white',0);

        $auto_smart_tag = data_get($data,'auto_smart_tag',null);
        $auto_smart_tag && $model -> auto_smart_tag = !is_array($auto_smart_tag) ? json_decode($auto_smart_tag,true):$auto_smart_tag;

        $auto_enterprise_tag = data_get($data,'auto_enterprise_tag',null);
        $auto_enterprise_tag && $model -> auto_enterprise_tag = !is_array($auto_enterprise_tag) ? json_decode($auto_enterprise_tag,true):$auto_enterprise_tag;

        $model -> open_keyword = data_get($data,'open_keyword',0);
        $model -> open_image = data_get($data,'open_image',0);
        $model -> open_default = data_get($data,'open_default',0);

        !empty($data['keyword_conf']) && $model -> keyword_conf = !is_array($data['keyword_conf']) ? self::formatData(json_decode($data['keyword_conf'],true),1):self::formatData($data['keyword_conf'],1);
        !empty($data['image_conf']) && $model -> image_conf = !is_array($data['image_conf']) ? self::formatData(json_decode($data['image_conf'],true),2):self::formatData($data['image_conf'],2);
        !empty($data['default_conf']) && $model -> default_conf = !is_array($data['default_conf']) ? self::formatData(json_decode($data['default_conf'],true),3):self::formatData($data['default_conf'],3);

        $model -> save();
        return $model;
    }

    /**
     * 初始化数据
     * $type 1关键词  2图片  3默认
     */
    public static  function  formatData($data,$type)
    {
        !is_array($data) && $data = json_decode($data,true);
        $newData = [];
        $guzze = $data['guzze'];
        switch ($type){
            case 1:
                $newData = [
                    'guzze' =>self::getData($guzze,self::$keywordStatic['guzze']),
                    'guide' =>$data['guide']
                ];
                break;
            case 2:
                $newData = [
                    'guzze' => self::getData($guzze,self::$imageStatic['guzze']),
                    'content' => CommonService::formatMsgContent($data['content'])['content']
                ];
                break;
            case 3:
                $newData = [
                    'guzze' => self::getData($guzze,self::$defaultStatic['guzze']),
                    'content' => CommonService::formatMsgContent($data['content'])['content'],
                    'delay' =>$data['delay']
                ];
                break;
        }
        return $newData;
    }

    public static function bindRobot($answerIds = [],$robotIds = [])
    {
        self::query() -> whereIn('id',$answerIds) -> update(['robot_ids'=>json_encode($robotIds)]);
    }

    private static function getData($data,$originData)
    {
        $new_data = [];
        foreach ($data as $key => $item){
            if(empty($originData[$item['key'] - 1])) continue;
            $newItem = [
                'key' => $item['key'],
                'text' => $originData[$item['key'] - 1]['text'],
                'checked' => $item['checked'],
                'value' => $item['value'],
                'help' => $originData[$item['key'] - 1]['help'],
            ];
            $new_data[] = $newItem;
        }
        return $new_data;
    }

}
